package mysql_conn

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

var dbs map[string]*gorm.DB

type DbConf struct {
	Name     string
	Host     string
	Username string
	Password string
	Port     int
	Database string
	Charset  string
	ServerId int
}

func init(){
	dbs = make(map[string]*gorm.DB, 3)
}

func (conf DbConf) GetName() string {
	return conf.Name
}

func (conf DbConf) GetDsn() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&loc=Local&parseTime=true", conf.Username, conf.Password, conf.Host, conf.Port, conf.Database, conf.Charset)
}

func (conf DbConf) InitGormDB() error {
	dsn := conf.GetDsn()
	mysqlDb := mysql.Open(dsn)

	db, err := gorm.Open(mysqlDb, &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	sqlDb, _ := db.DB()
	sqlDb.SetMaxIdleConns(5)
	sqlDb.SetMaxOpenConns(100)

	dbs[conf.Name] = db
	return err
}

func (conf DbConf) GroupGetDbByName() *gorm.DB {
	return GroupGetDbByName(conf.Name)
}

func (conf DbConf) GroupGetSessionByName() *gorm.DB {
	return GroupGetSessionByName(conf.Name)
}

func GroupGetDbByName(name string) *gorm.DB {
	v, ok := dbs[name]
	if !ok {
		return nil
	}
	return v
}

func GroupGetSessionByName(name string) *gorm.DB {
	v, ok := dbs[name]
	if !ok {
		return nil
	}

	if os.Getenv("APP_ENV") != "prod" {
		return v.Debug()
	}

	return v.Session(&gorm.Session{})
}
